package com.atguigu.lease.web.admin.service.imp;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioProperties minioProperties;


    @Override
    public String upload(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        InputStream inputStream = file.getInputStream();

        //连接桶信息
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();

        //声明一个文件名称
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);

        String uid = UUID.randomUUID().toString().replace("-", "");
        String datePath = new DateTime().toString("yyyy/MM/dd/");
        String fileName = datePath + uid + "." + filenameExtension;


        // 往这个桶内添加一张图片
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                // 读取文件(流)
                .stream(inputStream,file.getSize(),-1)
                //桶名称
                .bucket(minioProperties.getBucketName())
                //文件名
                .object(fileName) // 日期 + UUID.文件格式 如：2025/10/10/376f233a24bb43f782127ade5c442b45.png
                .build();


        minioClient.putObject(putObjectArgs);

        return minioProperties.getEndpoint() + "/" +  minioProperties.getBucketName() + "/" +fileName;
    }
}
